package com.gdsdxy.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gdsdxy.domain.User;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.gdsdxy.common.utils.FileUtils;
import com.gdsdxy.domain.Goods;
import com.gdsdxy.service.GoodsService;
import com.gdsdxy.service.GoodsTypeService;
@Controller
public class GoodsController {
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private GoodsTypeService service;

	// 跳转到新增页面
	@RequestMapping("toAddGoods")
	public String showadd(HttpServletRequest request, Model model) {
		model.addAttribute("gtlist", service.queryByLevel());
		return "/admin/addGoods";
	}
	// 商品新增
	@RequestMapping("addGoods")
	public String save(MultipartFile file[], Goods goods, HttpServletRequest request)
			throws IllegalStateException, IOException {
        File dir = FileUtils.createDir(request.getServletContext().getRealPath("/image"));

		File desFile = new File(dir, goods.getId()+".jpg");
		file[0].transferTo(desFile);

		System.out.println("huahuahualength"+file.length);

		for(int i=1;i<file.length;i++){
			File desFile1 = new File(dir,goods.getId()+"-"+(i+1)+".jpg");
			file[i].transferTo(desFile1);
		}

		goods.setPicture(dir.getName() + "/" + desFile.getName());
		goods.setFlag(1);//上架
		if (goodsService.save(goods)) {
			return "redirect:toAddGoods";
		} else {
			request.setAttribute("msg", "添加失败，重新再来");
			return "redirect:toAddGoods";
		}
	}
	// 查看商品详情
	@RequestMapping("getGoodsById")
	public String goodsbyid(int id, Model model) {
		model.addAttribute("goods", goodsService.querySingle(id));
		return "goodsDetail";
	}
	// 查看商品详情
	@RequestMapping("getGoodsIndex")
	@ResponseBody
	public List<List<Goods>> goodsindex(HttpServletResponse response) throws IOException {
		return goodsService.queryIndex();
	}
	// 查看商品列表
	@RequestMapping("getGoodsListByTn")
	public String goodsbytn(String tn, Model model) {
		model.addAttribute("typename",tn);
		model.addAttribute("glist", goodsService.queryByType(tn));
		return "goodsList";
	}
	// 查看商品列表
	@RequestMapping("getGoodsList")
	public String goodslist(Model model) {
		model.addAttribute("goodsList", goodsService.queryAll());
		return "admin/showGoods";
	}
	// 模糊查询商品列表
	@RequestMapping("selectByName")
	public String selectByName(String name, Model model) {
		model.addAttribute("glist", goodsService.queryByName(name));
		return "goodsList";
		}
	// 根据商品名称和上架时间查询商品（admin）
	@RequestMapping("selectByNameAndPub")
	public String queryNameAndPub(String name,String pubdate, Model model) {
		List<Goods> goods = goodsService.queryNameAndPub(name,pubdate);
		model.addAttribute("goodsList",goods );
		return "admin/showGoods";
		}
	//删除商品
	@RequestMapping("goodsDeleteById")
	public String goodsDeleteById(Integer id ,Model model) {
		goodsService.deleteById(id);
		return "redirect:getGoodsList";
	}
	//进入修改商品
	@RequestMapping("updateGoods")
	public String updateGoods(int id,Model model){
		model.addAttribute("gtlist", service.queryByLevel());
		model.addAttribute("goods", goodsService.querySingle(id));
		return "admin/updateGoods";
	}
	//修改商品
	@RequestMapping("updateGoodsById")
	public String update(MultipartFile file[], Goods goods, HttpServletRequest request)
			throws IllegalStateException, IOException {
		//只要数组的长度大于1才会修改覆盖图片
		if(file.length>1){
			System.out.println("aaa"+goods.getId()+"bbb"+goods.getPrice()+"cccc"+goods.getPicture()+"dddd"+file[0]+"eeee"+file.length);
			File dir = FileUtils.createDir(request.getServletContext().getRealPath("/image"));
			File desFile = new File(dir, goods.getId()+".jpg");
			//设置第一张图片的名称路径
			file[0].transferTo(desFile);
			//设置第二张图片开始的图片路径
			for(int i=1;i<file.length;i++){
				File desFile1 = new File(dir,goods.getId()+"-"+(i+1)+".jpg");
				file[i].transferTo(desFile1);
			}
		}
//		goods.setPicture(dir.getName() + "/" + desFile.getName());//设置图片路径
//		goods.setFlag(1);//上架
		goodsService.updateGoods(goods);
		return "redirect:getGoodsList";
	}

	//添加商品收藏
	@RequestMapping("insertCollectGoods")
	public String insertCollectGoods(int goodsId, HttpSession session,Model model){
		User user= (User) session.getAttribute("user");
		String gidStr=goodsService.selectCollectGoods(user.getUsername());
		String gids[]=gidStr.split(";");
		for(int i=0;i<gids.length;i++){
			if(gids[i].equals(String.valueOf(goodsId))){
				System.out.println("aaain");
				model.addAttribute("goods", goodsService.querySingle(goodsId));
				model.addAttribute("result","已收藏过此商品！去试试其他的吧");
				return "goodsDetailCollect";//已经收藏
			}
		}
		goodsService.insertCollectGoods(String.valueOf(goodsId),user.getUsername());
		System.out.println("aaaout");
		model.addAttribute("goods", goodsService.querySingle(goodsId));
		model.addAttribute("result","成功加入收藏夹！");
		return "goodsDetailCollect";//没有收藏
	}
	//查看收藏商品
	@RequestMapping("getCollectGoods")
	public String getCollectGoods(HttpSession session,Model model){
		User user= (User) session.getAttribute("user");
		String gidStr=goodsService.selectCollectGoods(user.getUsername());
		String gids[]=gidStr.split(";");
		//开头和结尾都是空的
		List<Goods> list=new ArrayList<>();
		for (int i=1;i<gids.length;i++){
			list.add(goodsService.querySingle(Integer.parseInt(gids[i])));
		}
		model.addAttribute("gList",list);
		return "collect";
	}
}
